package com.sk.weichat.ui.mucfile;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomSheetBehavior;
import android.support.design.widget.BottomSheetDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.sk.weichat.AppConstant;
import com.sk.weichat.R;
import com.sk.weichat.adapter.MucFileListAdapter;
import com.sk.weichat.bean.DateBean;
import com.sk.weichat.db.InternationalizationHelper;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.ui.me.PersonalCenterActivity;
import com.sk.weichat.ui.mucfile.bean.DownBean;
import com.sk.weichat.ui.mucfile.bean.MucFileBean;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.util.ViewPiexlUtil;
import com.sk.weichat.video.ChatVideoPreviewActivity;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.ListCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ArrayResult;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

import static com.sk.weichat.ui.mucfile.DownManager.STATE_DOWNLOADED;
import static com.sk.weichat.ui.mucfile.DownManager.STATE_DOWNLOADING;
import static com.sk.weichat.ui.mucfile.DownManager.STATE_PAUSEDOWNLOAD;

public class MucFileListActivity2 extends BaseActivity implements DownManager.DownLoadObserver {

    private static final int pageSize = 10;
    private int page = 0;
    private static final int REQUEST_CODE_SELECT_FILE = 10086;
    public int mRole;
    private String mRoomId;
    private String mUserId;
    private int mAllowUploadFile;
    private SmartRefreshLayout refreshLayout;
    private MucFileListAdapter mucFileListAdapter;

    private boolean isRefresh = true;

    private List<MultiItemEntity> data = new ArrayList<>();
    private BottomSheetDialog deletFileDialog;


    private LinkedHashMap<String, List<MucFileBean>> dataMap = new LinkedHashMap<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_muc_file_list);
        mRoomId = getIntent().getStringExtra("roomId");
        mRole = getIntent().getIntExtra("role", 3);
        mAllowUploadFile = getIntent().getIntExtra("allowUploadFile", 1);
        mUserId = coreManager.getSelf().getUserId();
        initActionBar();
        initView();
    }

    private void initActionBar() {
        getSupportActionBar().hide();
        findViewById(R.id.iv_title_left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        TextView tvTitle = (TextView) findViewById(R.id.tv_title_center);
        tvTitle.setText(InternationalizationHelper.getString("JXRoomMemberVC_ShareFile"));
        ImageView ivRight = (ImageView) findViewById(R.id.iv_title_right);
        ivRight.setImageResource(R.mipmap.icon_more_black);
        ivRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mAllowUploadFile == 1 || mRole == 1 || mRole == 2) {
                    Intent intent = new Intent(MucFileListActivity2.this, AddMucFileActivity2.class);
                    intent.putExtra("roomId", mRoomId);
                    startActivityForResult(intent, REQUEST_CODE_SELECT_FILE);
                } else {
                    ToastUtil.showToast(MucFileListActivity2.this, R.string.tip_cannot_upload);
                }
            }
        });
    }

    private void previewOrDownloadFile(MucFileBean bean) {
        Intent intent = null;
        if (bean.getState() == STATE_DOWNLOADED && bean.getType() == 1) {
            // 去打开
            intent = new Intent(MucFileListActivity2.this, MucFilePreviewActivity.class);
            intent.putExtra("data", bean);
        } else {
            // 去下载
            //判断本地文件是否存在
            File file = new File(DownManager.instance().getFileDir() + File.separator + bean.getName());
            if (bean.getState() == STATE_DOWNLOADED && (bean.getType() == 2 || bean.getType() == 3)) {
                intent = new Intent(MucFileListActivity2.this, ChatVideoPreviewActivity.class);
                intent.putExtra(AppConstant.EXTRA_VIDEO_FILE_PATH, file.getAbsolutePath());
            } else {
                intent = new Intent(MucFileListActivity2.this, MucFileDetails.class);
                intent.putExtra("data", bean);
            }
        }
        startActivity(intent);
    }

    private void initView() {
        TextView tvEmpty = findViewById(R.id.tv_empty);
        tvEmpty.setText("暂无群共享文件");
        RecyclerView recyclerView = findViewById(R.id.recyclerview);
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));

        mucFileListAdapter = new MucFileListAdapter(data);

        mucFileListAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            int pos;

            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                pos = position;
                MultiItemEntity item = data.get(position);
                if (item instanceof MucFileBean) {
                    switch (view.getId()) {
                        case R.id.iv_doc_type_icon:
                        case R.id.tv_doc_name:
                        case R.id.tv_doc_size:
                        case R.id.tv_bg:
                            //跳转
                            previewOrDownloadFile((MucFileBean) item);
                            break;
                        case R.id.iv_download:
                        case R.id.progressBar:
                            if (((MucFileBean) item).getState() == STATE_DOWNLOADING) {
                                //正在下载
                                DownManager.instance().pause((MucFileBean) item);
                            } else if (((MucFileBean) item).getState() == STATE_PAUSEDOWNLOAD) {
                                //已暂停
                                DownManager.instance().download((MucFileBean) item);
                            }
                            break;
                        case R.id.iv_delete:
                            //删除
                            View view1 = LayoutInflater.from(mContext).inflate(R.layout.bottom_sheet_dialog_delete_muc_file, null);
                            view1.findViewById(R.id.tv_delete_muc_file).setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    MucFileBean mucFileBean = (MucFileBean) data.get(pos);
                                    //删除群文件
                                    delNetFile(mucFileBean, pos);
                                    deletFileDialog.dismiss();
                                }
                            });
                            view1.findViewById(R.id.tv_delete_local_file).setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    //删除本地
                                    MucFileBean mucFileBean = (MucFileBean) data.get(pos);
                                    deleteLocalFile(mucFileBean, pos);
                                    deletFileDialog.dismiss();
                                }
                            });
                            view1.findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    //取消
                                    deletFileDialog.dismiss();
                                }
                            });

                            setupBottomSheetDialog(view1);

                            deletFileDialog.show();
                            //onDeleteClick((MucFileBean) item);
                            break;

                        case R.id.iv_avatar:
                        case R.id.tv_name:
                            Intent intent = new Intent(mContext, PersonalCenterActivity.class);
                            MucFileBean mucFileBean = (MucFileBean) data.get(pos);
                            intent.putExtra(AppConstant.EXTRA_USER_ID, mucFileBean.getUserId());
                            mContext.startActivity(intent);
                            break;

                    }
                }
            }
        });
        recyclerView.setAdapter(mucFileListAdapter);

        refreshLayout = findViewById(R.id.refreshLayout);
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                isRefresh = false;
                page++;
                getFileList(page, pageSize);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                isRefresh = true;
                page = 0;
                getFileList(page, pageSize);
            }
        });
        refreshLayout.autoRefresh();
    }

    private void setupBottomSheetDialog(View view) {
        if (deletFileDialog == null) {
            deletFileDialog = new BottomSheetDialog(mContext, R.style.bottomDialogNoBg);
            deletFileDialog.setCancelable(true);
            deletFileDialog.setCanceledOnTouchOutside(true);
            deletFileDialog.setContentView(view);
            final BottomSheetBehavior bottomSheetBehavior = BottomSheetBehavior.from((View) view.getParent());
            bottomSheetBehavior.setPeekHeight(ViewPiexlUtil.dp2px(mContext, 176));
            deletFileDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                }
            });
        }
    }

    public void getFileList(int page, int pageSize) {
        HashMap<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("roomId", mRoomId);
        params.put("pageSize", pageSize + "");
        params.put("pageIndex", "" + page);
        HttpUtils.get().url(coreManager.getConfig().UPLOAD_MUC_FILE_FIND_ALL)
                .params(params)
                .build()
                .execute(new ListCallback<MucFileBean>(MucFileBean.class) {
                    @Override
                    public void onResponse(ArrayResult<MucFileBean> result) {
                        refreshLayout.finishLoadMore();
                        refreshLayout.finishRefresh();
                        List<MucFileBean> datas = result.getData();
                        data.clear();
                        if (isRefresh) {
                            dataMap.clear();
                        }
                        Date date = new Date();
                        date.setTime(System.currentTimeMillis());
                        String currentMoth = sdf.format(date);
                        for (int i = 0; i < datas.size(); i++) {
                            date.setTime(datas.get(i).getTime() * 1000);
                            String dateStr = sdf.format(date);
                            if (dateStr.equals(currentMoth)) {
                                dateStr = "本月";
                            }
                            List<MucFileBean> list = dataMap.get(dateStr);
                            if (list == null) {
                                list = new ArrayList<>();
                                dataMap.put(dateStr, list);
                            }
                            // 获取本地下载状态
                            DownBean info = DownManager.instance().getDownloadState(datas.get(i));
                            datas.get(i).setState(info.state);
                            datas.get(i).setProgress(info.cur);
                            list.add(datas.get(i));
                        }
                        data.addAll(map2List());
                        mucFileListAdapter.notifyDataSetChanged();
                        mucFileListAdapter.expandAll();
                        if (data.size() == 0) {
                            adjustEmpty(true);
                        } else {
                            adjustEmpty(false);
                        }
                        if (datas.size() == 0) {
                            //隐藏加载进度
                            View view = refreshLayout.getRefreshFooter().getView().findViewById(R.id.srl_classics_progress);
                            view.setVisibility(View.INVISIBLE);
                            refreshLayout.finishLoadMoreWithNoMoreData();
                            refreshLayout.setEnableFooterFollowWhenNoMoreData(true);

                            Log.e("lzs", "view:" + view);
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {

                    }
                });
    }

    private List<MultiItemEntity> map2List() {
        List<MultiItemEntity> list = new ArrayList<>();
        Iterator<Map.Entry<String, List<MucFileBean>>> iter = dataMap.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<String, List<MucFileBean>> entry = iter.next();
            String date = entry.getKey();
            List<MucFileBean> listMucFiles = entry.getValue();
            DateBean dateBean = new DateBean();
            dateBean.setDate(date);
            for (int i = 0; i < listMucFiles.size(); i++) {
                dateBean.addSubItem(listMucFiles.get(i));
            }
            list.add(dateBean);
        }
        return list;
    }


    private void delNetFile(MucFileBean mucFileBean, int pos) {
        HashMap<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("roomId", mRoomId);
        params.put("userId", mUserId);
        params.put("shareId", mucFileBean.getShareId());

        HttpUtils.get().url(coreManager.getConfig().UPLOAD_MUC_FILE_DEL)
                .params(params)
                .build()
                .execute(new ListCallback<MucFileBean>(MucFileBean.class) {
                    @Override
                    public void onResponse(ArrayResult<MucFileBean> result) {
                        //
                        int parentPos = mucFileListAdapter.getParentPosition(mucFileBean);
                        boolean flag = data.remove(mucFileBean);
                        Date date = new Date();
                        date.setTime(mucFileBean.getTime() * 1000);
                        String dateStr = sdf.format(date);
                        date.setTime(System.currentTimeMillis());
                        String current = sdf.format(date);
                        if (dateStr.equals(current)) {
                            dateStr = "本月";
                        }
                        List<MucFileBean> list = dataMap.get(dateStr);
                        if (list != null) {
                            list.remove(mucFileBean);
                            if (list.size() == 0) {
                                dataMap.remove(dateStr);
                                data.remove(parentPos);
                                mucFileListAdapter.notifyItemRangeRemoved(parentPos, 2);
                            } else {
                                mucFileListAdapter.notifyItemRemoved(pos);
                            }
                        } else {

                        }
                        if (data.size() == 0) {
                            adjustEmpty(true);
                        } else {
                            adjustEmpty(false);
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        Log.e("lzs", "e:" + e.getMessage());
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_SELECT_FILE) {
            //刷新
            isRefresh = true;
            getFileList(0, (page + 1) * pageSize);
        }
    }

    private void deleteLocalFile(MucFileBean mucFileBean, int pos) {
        DownManager.instance().detele(mucFileBean);
        DownBean info = DownManager.instance().getDownloadState(mucFileBean);

        mucFileBean.setProgress(info.cur);
        mucFileBean.setState(info.state);

        mucFileListAdapter.notifyDataSetChanged();
    }

    static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月");


    @Override
    protected void onResume() {
        super.onResume();
        DownManager.instance().addObserver(this);
    }

    @Override
    protected void onDestroy() {
        DownManager.instance().deleteObserver(this);
        super.onDestroy();
    }

    @Override
    public void onDownLoadInfoChange(DownBean info) {
        // 实现单条刷新
        for (int i = 0; i < data.size(); i++) {
            MultiItemEntity bean = data.get(i);
            if (bean instanceof MucFileBean) {
                MucFileBean mucFileBean = (MucFileBean) bean;
                if (mucFileBean.getUrl().equals(info.url)) {
                    mucFileBean.setState(info.state);
                    mucFileBean.setProgress(info.cur);
                    mucFileListAdapter.notifyDataSetChanged();
                }
            }
        }
    }

    private void adjustEmpty(boolean visiable) {
        if (visiable) {
            findViewById(R.id.ll_layout_search_empty).setVisibility(View.VISIBLE);
        } else {
            findViewById(R.id.ll_layout_search_empty).setVisibility(View.GONE);
        }
    }

}
